package com.xyz.code.builder.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.mysql.jdbc.StringUtils;
import com.xyz.code.bean.AttrInfo;
import com.xyz.code.bean.MetaDataBean;
import com.xyz.code.builder.AbstractBuilder;
import com.xyz.code.util.Constants;
import com.xyz.code.util.MyFileUtil;
import com.xyz.code.util.PropertiesUtil;

public class BOBuilder extends AbstractBuilder {

	private boolean timeStampFlag = false;

	private boolean dateFlag = false;

	private boolean blobFlag = false;

	public BOBuilder(String tableName, String packageName, String outFileName,
			Map<String, String> map) {
		bean = new MetaDataBean(tableName, packageName, outFileName, map);
	}

	public String getImportInfo() {
		StringBuffer importInfo = new StringBuffer();
		if (bean.getPkAttrInfo() != null) {
			if ("Date".equalsIgnoreCase(bean.getPkAttrInfo().getJavaType())) {
				dateFlag = true;
			}
			if ("Timestamp"
					.equalsIgnoreCase(bean.getPkAttrInfo().getJavaType())) {
				timeStampFlag = true;
			}
			if ("Blob".equalsIgnoreCase(bean.getPkAttrInfo().getJavaType())) {
				blobFlag = true;
			}
		}
		for (AttrInfo info : bean.getAttrInfos()) {
			if ("Date".equalsIgnoreCase(info.getJavaType())) {
				dateFlag = true;
			}
			if ("Timestamp".equalsIgnoreCase(info.getJavaType())) {
				timeStampFlag = true;
			}
			if ("Blob".equalsIgnoreCase(info.getJavaType())) {
				blobFlag = true;
			}
		}
		if (timeStampFlag) {
			importInfo.append("import java.sql.Timestamp;\n");
		}
		if (dateFlag) {
			importInfo.append("import java.util.Date;\n");
		}
		if (blobFlag) {
			importInfo.append("import java.sql.Blob;\n");
		}
		return importInfo.toString();
	}

	public String getEntityInfo() {
		StringBuffer sb = new StringBuffer();
		processAllAttrs(sb, bean);
		processAllMethod(sb, bean);
		return sb.toString();
	}

	/**
	 * 解析输出属性
	 * 
	 * @return
	 */
	private void processAllAttrs(StringBuffer sb, MetaDataBean bean) {
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		String commDTO = PropertiesUtil
				.getConfigValueCache(Constants.CONFIG_FILE, Constants.COMMDTO);
		if (bean.getPkAttrInfo() != null) {
			if (bean.getPkAttrInfo().getComment() != null
					&& !"".equals(bean.getPkAttrInfo().getComment())) {
				Matcher m = p.matcher(bean.getPkAttrInfo().getComment());
				sb.append("\n\t/**\n\t * " + m.replaceAll("") + "\n\t */\n");
			}
			if (commDTO.toUpperCase().indexOf(
					bean.getPkAttrInfo().getFiledName().toUpperCase()) < 0) {
				sb.append("\tprivate " + bean.getPkAttrInfo().getJavaType()
						+ " " + bean.getPkAttrInfo().getFiledName()
						+ ";\r\n\n");
			}

			if ("Date".equalsIgnoreCase(bean.getPkAttrInfo().getJavaType())) {
				dateFlag = true;
			}
			if ("Timestamp"
					.equalsIgnoreCase(bean.getPkAttrInfo().getJavaType())) {
				timeStampFlag = true;
			}
		}
		for (AttrInfo info : bean.getAttrInfos()) {
			if (commDTO.toUpperCase()
					.indexOf(info.getFiledName().toUpperCase()) >= 0)
				continue;
			if (info.getComment() != null) {
				Matcher m = p.matcher(info.getComment());
				sb.append("\t/**\n\t * " + m.replaceAll("") + "\n\t */");
			}
			sb.append("\r\n");
			sb.append("\tprivate " + info.getJavaType() + " "
					+ info.getFiledName() + ";\r\n\n");
			if ("Date".equalsIgnoreCase(info.getJavaType())) {
				dateFlag = true;
			}
			if ("Timestamp".equalsIgnoreCase(info.getJavaType())) {
				timeStampFlag = true;
			}
		}
	}

	/**
	 * 生成所有的方法
	 * 
	 * @param sb
	 */
	private void processAllMethod(StringBuffer sb, MetaDataBean bean) {
		List<AttrInfo> infos = new ArrayList<AttrInfo>();
		if (bean.getPkAttrInfo() != null) {
			infos.add(bean.getPkAttrInfo());
		}
		infos.addAll(bean.getAttrInfos());
		String commDTO = PropertiesUtil
				.getConfigValueCache(Constants.CONFIG_FILE, Constants.COMMDTO);
		for (AttrInfo info : infos) {
			if (commDTO.toUpperCase()
					.indexOf(info.getFiledName().toUpperCase()) >= 0)
				continue;
			sb.append("\n\tpublic void " + info.getSetMethod() + "("
					+ info.getJavaType() + " " + info.getFiledName()
					+ "){\r\n");
			sb.append("\t\tthis." + info.getFiledName() + " = "
					+ info.getFiledName() + ";\r\n");
			sb.append("\t}\r\n");

			sb.append("\n\tpublic " + info.getJavaType() + " "
					+ info.getGetMeth() + "(){\r\n");
			sb.append("\t\treturn this." + info.getFiledName() + ";\r\n");
			sb.append("\t}\r\n");
		}
	}

	public static void main(String[] args) {
		// MetaDataBean bean = new MetaDataBean("product_attr",
		// "com.ctg.itrdc.product");
		// System.out.println(new BOBuilder("PZ_GG_SERVICE_OFFER",
		// "com.ctg.itrdc.product",""));
	}

	@Override
	public void builder() {
		String str = "";
		try {
			str = MyFileUtil.getContextByTemplate(this, getTemplate());
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {

			OutputStreamWriter write = new OutputStreamWriter(
					new FileOutputStream(new File(getBaseDir() + "Abstract"
							+ bean.getClassName() + "BO.java")),
					"UTF-8");

			BufferedWriter writer = new BufferedWriter(write);

			writer.write(str);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getBaseDir() {
		String[] paths = bean.getBasePackage().split("\\.");
		String outFile = bean.getOutFileName();
		String fileDir = "out/service/src/main/java/";
		if (!StringUtils.isNullOrEmpty(outFile)) {
			fileDir = outFile + fileDir;
		}
		for (String path : paths) {
			fileDir = fileDir + path + "/";
		}
		fileDir += "bo/";
		File file = new File(fileDir);
		file.mkdirs();
		return fileDir;
	}

	@Override
	public String getTemplate() {
		// TODO Auto-generated method stub
		return "template/model/bo/${className}BO.tpl";
	}

}
